# coding=utf-8
import numpy as np
import cv2
from sklearn.datasets import load_sample_image
from sklearn.cluster import KMeans, MiniBatchKMeans
from os.path import dirname, join

import sys
from time import gmtime, strftime
#from PIL import Image
#import matplotlib.pyplot as plt

def rdis_wall(input_file, color_file, result_file, file_path):
#    print("--- kmeans,%s ---" % os.environ["HOME"] )
    print("--- kmeans,%s  %s   %s ---" % (input_file, color_file, result_file) )
    #filename = join(dirname(__file__), "filename.txt")      #--- kmeans,/data/user/0/com.octopus.didi/files/chaquopy/AssetFinder/app/filename.txt  --
    print( "--- kmeans start, %s  %s---" % ( sys._getframe().f_lineno, strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) ) )
    dataOrigin = cv2.imread( input_file );

    (height, width, channels) = dataOrigin.shape;
    data = dataOrigin.reshape(height*width, 3);
    knum = 3;

    kmeansPredicter = KMeans( n_clusters = knum );
    clt_1 = kmeansPredicter.fit(data);

    temp = kmeansPredicter.predict(data);
    dataNew = kmeansPredicter.cluster_centers_[temp];
    dataNew.shape = dataOrigin.shape;

    print( "--- kmeans, %s  %s---" % ( sys._getframe().f_lineno, strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) ) )
    dataNew = np.array( dataNew ).astype( int );
    cv2.imwrite(result_file, dataNew);

    palette = np.zeros((100, width, 3));
    steps = width/clt_1.cluster_centers_.shape[0];
    print( "--- kmeans, %s  %s---" % ( sys._getframe().f_lineno, strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) ) )
    for idx, centers in enumerate(clt_1.cluster_centers_):
        palette[:, int(idx*steps):(int((idx+1)*steps)), :] = centers;
    colorcut = np.array(palette).astype(int);
    cv2.imwrite(color_file, colorcut);

    print( "--- kmeans, %s  %s---" % ( sys._getframe().f_lineno, strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) ) )
    num = int(colorcut.shape[1] / knum / 2);
    #dataNewcopy = np.array(dataNew).astype(int);
    #colorstandard = [ ];
    for i in range(0, knum):
        colorchoice = colorcut[50,(num*(1+2*i)),:];
        dataNewcopyqq = dataNew;
        strname = 'result' + str(i) + '.jpg';
        datafd = np.zeros((dataNewcopyqq.shape[0], dataNewcopyqq.shape[1], 3));
        print( ">>>for>>>> kmeans, %s  %s---" % ( sys._getframe().f_lineno, strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) ) )
        for j in range(0, dataNewcopyqq.shape[0]):
            for k in range(0, dataNewcopyqq.shape[1]):
                #if dataNewcopyqq[j,k,:].all != colorchoice.all:
                if abs(dataNewcopyqq[j,k,0] - colorchoice[0])<5 and abs(dataNewcopyqq[j,k,1] - colorchoice[1])<5 and abs(dataNewcopyqq[j,k,2] - colorchoice[2])<5:
                    datafd[j,k,0] = dataNewcopyqq[j,k,0];
                    datafd[j,k,1] = dataNewcopyqq[j,k,1];
                    datafd[j,k,2] = dataNewcopyqq[j,k,2];
                else:
                    #dataNewcopyqq[j,k,:] = [0,0,0];
                    datafd[j,k,0] = 255;
                    datafd[j,k,1] = 255;
                    datafd[j,k,2] = 255;
                    #print('True');
        #colorstandard.append(dataNewcopyqq);
        #cv2.imwrite(strname, datafd);  #/storage/emulated/0/Android/data/com.octopus.didi/files
        print( ">>>>>end>>>>>kmeans, %s  %s---" % ( sys._getframe().f_lineno, strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) ) )
        cv2.imwrite(file_path + strname, datafd);